window.onload = function(){
    var userTriggerDOM = document.getElementById("userTrigger");
    var userInputDOM = document.getElementById("userInput");
    
    var contentTriggerDOM = document.getElementById("contentTrigger");
    var contentInputDOM = document.getElementById("contentInput");

    var emojiTriggerDOM = document.getElementById("emojiTrigger");
    var emojiesDOM = document.getElementById("emojies");
    var emojiDOMs = document.querySelectorAll(".emoji");
    var talk4DOM = document.querySelector(".talk4");

    var sendTriggerDOM = this.document.getElementById("sendTrigger");

    var nickName = document.querySelector(".nickName").innerHTML;
    var toUserName;
    var role = document.getElementsByClassName('nickName')[0].getAttribute("data-role");//管理员or普通用户
    console.log(role);
    
    userTriggerDOM.onclick = function(){
        userTriggerDOM.style.display = "none";
        userInputDOM.style.display = "inline-block";
        userInputDOM.focus();
    }
    contentTriggerDOM.onclick = function(){
        contentTriggerDOM.style.display = "none";
        contentInputDOM.style.display = "inline-block";
        contentInputDOM.focus();
    }
    emojiTriggerDOM.onclick = function(){
        emojiTriggerDOM.style.display = "none";
        emojiesDOM.style.display = "block";
        talk4DOM.style.overflow = "auto";
    }

    for(var i=0;i<emojiDOMs.length;i++){
        emojiDOMs[i].onclick = function(){
            console.log(this);
            for(var i=0;i<emojiDOMs.length;i++){
                emojiDOMs[i].classList.remove("emojiSelected");
            }
            this.classList.add("emojiSelected");

        }
    }

    function getUsername() {
        var userDOMs = document.querySelectorAll(".user");
        for(var i=0;i<userDOMs.length;i++){
            userDOMs[i].onclick = function(){
                toUserName = this.innerText;
                console.log(toUserName,userInputDOM.style.display)
                if(userInputDOM.style.display!=""){
                    userInputDOM.value = toUserName;
                }else{
                    userTriggerDOM.style.display = "none";
                    userInputDOM.style.display = "inline-block";
                    userInputDOM.value = toUserName;
                }
            }
        }
    }

    //websocket配置
    var webSocket;
    if ("WebSocket" in window) {
        webSocket = new WebSocket("ws://localhost:8080/websocket/"+document.getElementsByClassName('nickName')[0].innerHTML);
        webSocket.onopen = function()
        {
            //webSocket.send( document.getElementById('username').value+"已经上线了");
            console.log("已经连通了websocket");
        };
        sendTriggerDOM.onclick = send;
        webSocket.onmessage = function (ev) {
            var message_data = ev.data;
            var data = JSON.parse(message_data);
            console.log(data);
            if (data.messageType === 1 ) {
                setNotifyInnerHTML(data,"上线了!");
                updateOnlineNum(data);
            } else if (data.messageType === 2) {
                setNotifyInnerHTML(data,"下线了!");
                updateOnlineNum(data);
            } else if (data.messageType === 3) {
                setMessageInnerHTML(data)
            } else {
                var testName = data.fromUsername;
                if (data.state){
                    setNotifyInnerHTML(data,"被解除禁言");
                    document.querySelector("input[data-nickname=lv"+testName+"]").src = "../images/voice.png";
                    if (nickName==data.fromUsername){
                        recoverSend();
                    }
                } else {
                    setNotifyInnerHTML(data,"被禁言");
                    document.querySelector("input[data-nickname=lv"+testName+"]").src = "../images/silence.png"
                    if (nickName==data.fromUsername){
                        forbidSend();
                    }
                }
            }
        };
    }

    function setNotifyInnerHTML(data, text) {
        var msgContainerDOM = document.querySelector(".msgContainer");
        var msg = "<div class='msg'>"+
            "系统消息："+"<span class='fromUser'>"+data.fromUsername+"</span>" + text + "<span class='date'>" +
            new Date().Format("yyyy-MM-dd hh:mm:ss") +"</span>"+
            "</div>";
        msgContainerDOM.innerHTML += msg;
    }

    function setMessageInnerHTML(data) {
        var msgContainerDOM = document.querySelector(".msgContainer");
        var toUsername = data.toUsername;
        if (toUsername == null){
            toUsername = "所有人"
        }
        var msg = "<div class='msg'>"+
            "<span class='fromUser'>"+data.fromUsername+"</span><span class='smile'>" + data.emotion +
            "</span>对<span class='toUser'>"+toUsername+"</span>说：" +
            "<span class='content'>"+data.message+"</span>" +
            "<span class='date'>"+ data.date +"</span>"+
            "</div>";
        msgContainerDOM.innerHTML += msg;
    }

    //更新在线人数并添加
    function updateOnlineNum(data) {
        document.getElementsByClassName('left')[0].innerHTML = '<div class="title1">\n' +
            '用户在线人数：<span id="nums">' + data.onlineUsers.length + '</span>\n' +
            '</div>';
        for (var i = 0; i < data.onlineUsers.length; i++) {
            console.log(i);
            var state;
            console.log(data.onlineUsers[i].state)
            if (data.onlineUsers[i].state){
                state = "<input type='image' src='../images/voice.png' class='voice' data-nickname='"+"lv"+data.onlineUsers[i].username+"' onclick='forbidVoice(this,\""+role+"\",\""+data.onlineUsers[i].username+"\")'>";
            }else {
                state = "<input type='image' src='../images/silence.png' class='voice' data-nickname='"+"lv"+data.onlineUsers[i].username+"' onclick='forbidVoice(this,\""+role+"\",\""+data.onlineUsers[i].username+"\")'>";
                if (data.onlineUsers[i].username==nickName){
                    forbidSend();
                }
            }
            console.log(state);
            document.getElementsByClassName('left')[0].innerHTML += "<div class=\"user\">" +
                data.onlineUsers[i].username + state + "</div>"
        }
        getUsername()
    }
    


    function send(){
        var content = contentInputDOM.value;
        var msgContainerDOM = document.querySelector(".msgContainer");
        var date = new Date().Format("yyyy-MM-dd hh:mm:ss");
        if(content!=""){
            var toNickName;
            var emoji = "";
            if(userInputDOM.value==""){
                toNickName = "所有人"
            }else{
                toNickName = userInputDOM.value
            }
            if(document.querySelector(".emojiSelected")!=null){
                emoji = document.querySelector(".emojiSelected").innerHTML.trim();
            }
            var message = {
                "message": content,
                "fromUsername": nickName,
                "toUsername": toNickName,
                "date" : date,
                "emotion": emoji
            };
            if (toNickName!="所有人"){
                setMessageInnerHTML(message);
            }
            //websocket发送消息
            webSocket.send(JSON.stringify(message));
        }else{
            alert("发送信息不能为空");
        }
    }
    
    function forbidSend() {
        sendTriggerDOM.onclick = forbidSend;
        contentInputDOM.placeholder = "您已被禁言";
        contentInputDOM.disabled = "disabled";
        console.log("你被禁言啦");
    }
    
    function recoverSend() {
        sendTriggerDOM.onclick = send;
        contentInputDOM.placeholder = "说些什么......";
        contentInputDOM.disabled = "";
        console.log("恢复正常");
    }
};
Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
function forbidVoice(e,role,nickname) {
    if (role=="管理员"){
        var src = e.src.substring(e.src.lastIndexOf("/")+1);
        if (src=="voice.png"){
            e.src = "../images/silence.png";
        }else {
            e.src = "../images/voice.png";
        }
        axios({
            method: 'get',
            url: '/forbidden?nickname='+nickname,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(function (value) {
            var data = value.data;
            console.log(data);
        });
    }
}